<script lang="ts" setup>
import type { FormInstance } from 'ant-design-vue'
import { notification } from 'ant-design-vue'
import { cloneDeep } from 'lodash'
import type { PurchaseDetailModel } from '@/api/purchase/purchase-list.ts'
import { createPurchaseInfo, updatePurchaseInfo } from '@/api/purchase/purchase-list.ts'
import { PlusOutlined } from "@ant-design/icons-vue"
import {defineComponent, ref} from "vue"
import dayjs, { Dayjs } from 'dayjs'

const dateFormat = 'YYYY/MM/DD'
let value1 = ref<Dayjs>()

const emit = defineEmits(['cancel', 'ok'])

const isUpdate = ref(false)

const visible = ref(false)

const title = computed(() => {
  return isUpdate.value ? '编辑采购单' : '新增采购单'
})

const formRef = ref<FormInstance>()

const formData = ref<PurchaseDetailModel>()

const labelCol = { style: { width: '100px' } }
const wrapperCol = { span: 24 }

// 发车日期格式化
function onPDChange(value, dateString) {
  value1 = value
  if (dateString !=''){
    formData.value.purchaseDeparture = dayjs(dateString).format('YYYY-MM-DD')
  }
}

function open(record?: PurchaseDetailModel) {
  console.log('进入采购单open方法')
  visible.value = true
  isUpdate.value = !!record?.purchaseId
  formData.value = cloneDeep(record) ?? {
    purchaseId: undefined,
    purchaseName: undefined,
    purchaseDesc: undefined,
    purchaseStatus: undefined,
    purchaseType: undefined,
    purchaseAmount: undefined,
    purchaseDate: undefined,
    purchaseRemark: undefined,
    purchaseUserId: undefined,
    purchaseUserName: undefined,
    purchaseActualAmount: 0,
    purchaseFreight: 0,
  }
}

async function handleOk() {
  try {
    await formRef.value?.validate()
    // 如果是编辑，则进入编辑调用接口
    if (isUpdate.value) {
      console.log(formData.value)
      formData.value.items=[]
      formData.value.purchaseStatus = 2
      // 进入新增接口
      const res = await updatePurchaseInfo(formData.value)
      if (res.code === 200) {
        notification.success({
          message: '修改完成',
          duration: 3,
        })
        visible.value = false
      } else {
        notification.error({
          message: res.msg,
          duration: 3,
        })
      }
      visible.value = false
    }else {
      console.log(formData.value)
      if (formData.value.purchaseDeparture === ""){
        formData.value.purchaseDeparture = dayjs(value1.value).format('YYYY-MM-DD')
      }
      formData.value.purchaseStatus = 2
      // 进入新增接口
      const res = await createPurchaseInfo(formData.value)
      if (res.code === 200) {
        notification.success({
          message: '添加成功',
          duration: 3,
        })
        visible.value = false
      }else {
        notification.error({
          message: res.msg,
          duration: 3,
        })
      }
    }
  }
  catch (errorInfo) {
    console.log('Form Validate Failed:', errorInfo)
  }
}

function handleCancel() {
  formRef.value?.resetFields()
  emit('cancel')
}


const VNodes = defineComponent({
  props: {
    vnodes: {
      type: Object,
      required: true,
    },
  },
  render() {
    return this.vnodes
  },
})

let index = 0
const items = ref(['鲁FP58E2', '鲁FBJ831', '鲁FDM928','鲁FCL060','鲁FCV332','鲁FBK667'])
const value = ref()
const inputRef = ref()
const name = ref()

const addItem = e => {
  e.preventDefault()
  console.log('addItem')
  items.value.push(name.value || `New item ${(index += 1)}`)
  name.value = ''
  setTimeout(() => {
    inputRef.value?.focus()
  }, 0)
}

defineExpose({
  open,
})
</script>

<template>
  <a-modal v-model:open="visible" :title="title" @ok="handleOk" @cancel="handleCancel">
    <a-form ref="formRef" :model="formData" class="w-full" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item name="value1" :rules="[{ required: false, message: '请选择本单日期' }]" label="本单日期">
        <a-date-picker v-model:value="value1" format="YYYY-MM-DD" style="width: 100%" @change="onPDChange"/>
      </a-form-item>
      <a-form-item name="purchaseVehicle" :rules="[{ required: true, message: '请输入采购车辆' }]" label="采购车辆">
        <a-select v-model:value="formData.purchaseVehicle" placeholder="请选择采购车辆" :options="items.map(item => ({ value: item }))">
          <template #dropdownRender="{ menuNode: menu }">
            <v-nodes :vnodes="menu" />
            <a-divider style="margin: 4px 0" />
            <a-space style="padding: 4px 8px">
              <a-input ref="inputRef" v-model:value="name" placeholder="请输入车辆信息" />
              <a-button type="text" @click="addItem">
                <template #icon>
                  <plus-outlined />
                </template>
                添加车辆
              </a-button>
            </a-space>
          </template>
        </a-select>
      </a-form-item>
      <a-form-item name="purchaseUser" label="采购人" :rules="[{ required: true, message: '请填写采购人' }]">
        <a-input v-model:value="formData.purchaseUser" placeholder="请填写采购人" />
      </a-form-item>
      <a-form-item name="purchaseFreight" label="本次运费总价" :rules="[{ required: true, message: '请输入运费总价' }]">
        <a-input-number :min="0" v-model:value="formData.purchaseFreight" addon-after="￥" placeholder="请输入运费总价" :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"/>
      </a-form-item>
      <a-form-item name="purchaseActualAmount" label="实际采购总金额" :rules="[{ required: true, message: '请输入实际采购总金额' }]" :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')">
        <a-input-number :min="0" v-model:value="formData.purchaseActualAmount" addon-after="￥" placeholder="请输入实际采购总金额" />
      </a-form-item>
      <a-form-item name="purchaseDescribe" label="采购单描述">
        <a-textarea v-model:value="formData.purchaseDescribe" placeholder="请填写描述信息" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>